#!/bin/bash

# Dubbo + Nacos 示例启动脚本

set -e

echo "========================================="
echo "  Dubbo + Nacos 示例启动脚本"
echo "========================================="

# 检查 Nacos 是否运行
echo ""
echo "1. 检查 Nacos 服务..."
if curl -s http://localhost:8848/nacos/v1/console/health/readiness > /dev/null 2>&1; then
    echo "   ✅ Nacos 正在运行"
else
    echo "   ❌ Nacos 未运行，请先启动 Nacos："
    echo "      cd ../.. && ./scripts/start-nacos.sh"
    exit 1
fi

# 编译项目
echo ""
echo "2. 编译项目..."
mvn clean package -DskipTests
echo "   ✅ 编译完成"

# 启动 Provider
echo ""
echo "3. 启动 Dubbo Provider..."
cd dubbo-provider
nohup java -jar target/dubbo-provider-1.0.0.jar > provider.log 2>&1 &
PROVIDER_PID=$!
echo "   ✅ Provider 启动中... (PID: $PROVIDER_PID)"
echo "   日志文件: dubbo-provider/provider.log"
cd ..

# 等待 Provider 启动
echo ""
echo "4. 等待 Provider 注册到 Nacos..."
sleep 10

# 启动 Consumer
echo ""
echo "5. 启动 Dubbo Consumer..."
cd dubbo-consumer
nohup java -jar target/dubbo-consumer-1.0.0.jar > consumer.log 2>&1 &
CONSUMER_PID=$!
echo "   ✅ Consumer 启动中... (PID: $CONSUMER_PID)"
echo "   日志文件: dubbo-consumer/consumer.log"
cd ..

# 等待 Consumer 启动
echo ""
echo "6. 等待服务启动..."
sleep 10

# 检查服务状态
echo ""
echo "========================================="
echo "  启动完成！"
echo "========================================="
echo ""
echo "📊 服务信息："
echo "  Provider PID: $PROVIDER_PID"
echo "  Consumer PID: $CONSUMER_PID"
echo ""
echo "🔗 访问地址："
echo "  Nacos 控制台: http://localhost:8848/nacos"
echo "  Consumer API: http://localhost:8082/api/users"
echo ""
echo "🧪 测试命令："
echo "  curl http://localhost:8082/api/users"
echo "  curl http://localhost:8082/api/users/1"
echo ""
echo "📝 查看日志："
echo "  tail -f dubbo-provider/provider.log"
echo "  tail -f dubbo-consumer/consumer.log"
echo ""
echo "🛑 停止服务："
echo "  ./stop-all.sh"
echo ""
echo "========================================="

# 保存 PID
echo $PROVIDER_PID > provider.pid
echo $CONSUMER_PID > consumer.pid

